//
//  DLHomeViewController.swift
//  新浪微博
//
//  Created by 周冰烽 on 2016/12/30.
//  Copyright © 2016年 周冰烽. All rights reserved.
//

import UIKit

//定义全局常量,尽量使用private修饰,否则导出都可以访问
fileprivate let cellID = "cellID"
class DLHomeViewController: DLBaseViewController {
    
    /// 微博数据数组
    fileprivate lazy var status = [String]()
    
    //用网络工具加载微博工具
    
    
    
    /// 加载数据
    override func loadData() {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["access_token":"2.00NoFbNDh7exfB589d0c2199wQ9z2E"]
//        DLNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (_, json) in
//            print(json ?? "")
//        }) { (_, error) in
//            print("网络请求失败\(error)")
//        }
        DLNetworkManager.shared.request(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            print(json ?? "")
        }
        print("开始加载数据\(DLNetworkManager.shared)")
        //模拟'延时'加载数据 -> dispatch_after
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
            for i in 0..<20 {
                if self.isPullup {
                    self.status.append("上拉\(i)")
                }else {
                    //将数据出入到数组的顶部
                    self.status.insert(i.description, at: 0)
                }
            }
            print("刷新表格")
            print("数据刷新完毕")
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            self.isPullup = false
            self.tableView?.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    @objc fileprivate func showFriends() {
        print(#function)
        let vc = DLDemoViewController()
        //vc.hidesBottomBarWhenPushed = true
        //push的动作时 nav 做的
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 表格数据源方法,具体的数据源方法实现,不需要super
extension DLHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return status.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //1.取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
        //2.设置cell
        cell.textLabel?.text = status[indexPath.row]
        //3.返回cell
        return cell
    }
}
// MARK: - 设置界面
extension DLHomeViewController {
    override func setupUI(){
        super.setupUI()
        //设置导航栏左按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
        //注册原型cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
    }
}
